﻿package com.badibadi.activity;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;

import com.badibadi.adapter.AreaAdapter;
import com.badibadi.infos.AreaModel;
import com.badibadi.infos.Results;
import com.badibadi.mytools.AreaDialog;
import com.badibadi.mytools.Constants;
import com.badibadi.mytools.DisplayUtil;
import com.badibadi.mytools.JSONUtils;
import com.badibadi.mytools.MySharePreferences;
import com.badibadi.mytools.RegexUtils;
import com.badibadi.mytools.Utils;
import com.badibadi.uniclubber.R;
//import com.lidroid.xutils.util.LogUtils;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.content.Intent;
import android.graphics.Paint;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class RegirstrationActivity extends BaseActivity implements // regirstration
		OnClickListener {

	private TextView btn_login;// 点击转为登陆界面
	private TextView from;// 来自
	private EditText et_userName, et_password, et_confirm_password, et_mail,
			et_sex;
	private Button regirstration;
	private boolean isRun = true;
	private List<AreaModel> areaModelscountry, areaModelssheng, areaModelscity;
	// private HolderView holderView;
	private AreaAdapter areaAdapter;
	private String country = null, sheng = null, city = null, area_id = null,
			sex_temp = null;
	private Message mes;
	private Bundle bun;
	private int languageType = 0;
	private MySharePreferences preferences;
	private AreaDialog areaDialog;

	private Map<String, Object> map;
	/**
	 * 向下一个界面传送数据的key
	 */
	private String Key = "RegirstrationActivity";
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				Utils.ExitPrgress(RegirstrationActivity.this);
				// Is_Area_Dialog(RegirstrationActivity.this);
				areaDialog.AreaDisplayDialog();
				areaAdapter = new AreaAdapter(RegirstrationActivity.this,
						areaDialog.areaModelscountry);
				areaDialog.holderView.area_country_name_spinner
						.setAdapter(areaAdapter);
				// holderView.area_country_name_spinner.setAdapter(areaAdapter);
				break;
			case 2:// 链接网络出错
				Utils.ExitPrgress(RegirstrationActivity.this);
				try {
					Utils.showMessage(
							RegirstrationActivity.this,
							getResources().getString(
									R.string.NetworkConnectionFailure));
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			case 3:
				Utils.ExitPrgress(RegirstrationActivity.this);
				areaAdapter = new AreaAdapter(RegirstrationActivity.this,
						areaDialog.areaModelssheng);
				areaDialog.holderView.area_province_name_spinner
						.setAdapter(areaAdapter);
				// holderView.area_province_name_spinner.setAdapter(areaAdapter);
				break;
			case 4:
				Utils.ExitPrgress(RegirstrationActivity.this);
				areaAdapter = new AreaAdapter(RegirstrationActivity.this,
						areaDialog.areaModelscity);
				areaDialog.holderView.area_city_name_spinner
						.setAdapter(areaAdapter);
				// holderView.area_city_name_spinner.setAdapter(areaAdapter);
				break;
			case 5:
				Utils.ExitPrgress(RegirstrationActivity.this);
				Utils.showMessage(RegirstrationActivity.this, getResources()
						.getString(R.string.l_regirstration_scross));
				Intent intent = new Intent(RegirstrationActivity.this,
						ValidationEmailActivity.class);
				intent.putExtra(Key, "" + et_mail.getText().toString().trim());
				startActivity(intent);
				break;
			case 6:
				Utils.ExitPrgress(RegirstrationActivity.this);
				Utils.showMessage(RegirstrationActivity.this, getResources()
						.getString(R.string.l_regirstration_falit));
				break;
			case 7:
				String[] display = msg
						.getData()
						.getString("来自",
								getResources().getString(R.string.l_x2))
						.split(" ");
				if (display != null && display.length > 0) {
					from.setText(display[0] + " " + display[1] + " "
							+ display[2]);
					area_id = display[3];
				} else {
					from.setText(getResources().getString(R.string.l_x2));
					area_id = null;
				}

				break;
			default:
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setFullScreen();
		setContentView(R.layout.regirstration);
		init();
	}

	private void init() {
		// TODO Auto-generated method stub
		// holderView = new HolderView();
		preferences = new MySharePreferences(getApplicationContext(),
				"language");
		languageType = preferences.get("language", 0);
		et_userName = (EditText) findViewById(R.id.e_mail);
		et_password = (EditText) findViewById(R.id.password);
		et_confirm_password = (EditText) findViewById(R.id.confirm_password);
		et_sex = (EditText) findViewById(R.id.sex);
		et_mail = (EditText) findViewById(R.id.mail);
		areaDialog = new AreaDialog(RegirstrationActivity.this, languageType,
				handler);

		et_sex.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				setSexDialog(RegirstrationActivity.this);
				setOnMyDialogeClistener(new OnMyDialogeClistener() {

					@Override
					public void Ok() {
						// TODO Auto-generated method stub

						et_sex.setText("" + getSex());
						if (et_sex
								.getText()
								.toString()
								.trim()
								.equals(getResources().getString(R.string.l_x3))) {
							sex_temp = "2";
						} else if (et_sex
								.getText()
								.toString()
								.trim()
								.equals(getResources().getString(R.string.l_x4))) {
							sex_temp = "1";
						} else {
							sex_temp = "0";
						}
					}

					@Override
					public void Cancle() {
						// TODO Auto-generated method stub

					}
				});

			}
		});
		this.findViewById(R.id.regirstration).setOnClickListener(this);

		btn_login = (TextView) findViewById(R.id.reg_login);
		btn_login.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); // 添加线
		btn_login.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				startActivity(new Intent(RegirstrationActivity.this,
						LoginActivity.class));
				RegirstrationActivity.this.finish();
			}
		});
		from = (TextView) this.findViewById(R.id.from);
		from.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// Getareathread("" + languageType);// 主动获取国家数据
				// setFromDialog(RegirstrationActivity.this);
				Utils.showPrgress(RegirstrationActivity.this);
				areaDialog.Getareathread();
			}
		});
	}

	private View getSexView() {
		// TODO Auto-generated method stub
		int dip5_px = DisplayUtil.dip2px(RegirstrationActivity.this, 5);
		LinearLayout ll = new LinearLayout(RegirstrationActivity.this);
		ll.setOrientation(LinearLayout.VERTICAL);
		/** 国家 */
		LinearLayout l1 = new LinearLayout(RegirstrationActivity.this);
		l1.setOrientation(LinearLayout.HORIZONTAL);
		Spinner spinner1 = new Spinner(RegirstrationActivity.this);
		spinner1.setLayoutParams(new LinearLayout.LayoutParams(
				LayoutParams.WRAP_CONTENT, DisplayUtil.dip2px(
						RegirstrationActivity.this, 50), 1));
		spinner1.setBackgroundResource(R.drawable.shape_layout_bg);
		String[] arr1 = getResources().getStringArray(R.array.sex);
		TextView tv1 = new TextView(RegirstrationActivity.this);
		tv1.setText(R.string.sex);
		tv1.setPadding(dip5_px, 0, 0, 0);
		ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(
				RegirstrationActivity.this,
				android.R.layout.simple_list_item_1, arr1);
		spinner1.setAdapter(adapter1);
		l1.addView(tv1);
		l1.addView(spinner1);
		l1.setPadding(0, dip5_px, dip5_px, dip5_px);
		return l1;
	}

	private void Getareathread(final String type) {
		Utils.showPrgress(RegirstrationActivity.this);
		new Thread(new Runnable() {
			@Override
			public void run() {
				Map<String, Object> map = new HashMap<String, Object>();

				int t = Integer.parseInt(type);
				switch (t) {
				case 0:
					map.put("languageType", "cn_name");
					break;
				case 1:
					map.put("languageType", "en_name");
					break;
				case 2:
					map.put("languageType", "tw_name");
					break;
				}
				String content = Utils.sendRequest(map, Constants.BadiUrl
						+ "area");
				if (content != null) {
					//    ("结果是:" + content);
					Results results = Utils.checkResult_NNN(
							getApplicationContext(), content);
					if (results != null && results.getRetmsg() != null) {
						//    ("得到的结果是：" + results.getRetmsg());
						try {
							areaModelscountry = Utils.getListByJsonString(
									results.getRetmsg(), AreaModel.class);
							handler.sendEmptyMessage(1);
						} catch (JSONException e) {
//							   ("解析出错");
							   
						}
					}
				} else {
					handler.sendEmptyMessage(2);
				}
			}
		}).start();
	}

	private void PutUser_Infos(final String userName, final String password,
			final String email, final String area_id, final String sex) {
		Utils.showPrgress(RegirstrationActivity.this);
		new Thread(new Runnable() {
			@Override
			public void run() {
				mes = new Message();
				bun = new Bundle();
				map = new HashMap<String, Object>();
				map.put("userName", userName);
				map.put("password", password);
				map.put("email", email);
				map.put("area_id", area_id);
				map.put("sex", sex);
				map.put("lang", com.badibadi.mytools.Dialog
						.getSystemLanguageTypegy(RegirstrationActivity.this));
				String content = Utils.sendRequest(map, Constants.BadiUrl
						+ "register");
//				   
//				LogUtils.i("注册提交上去的数据是:" + map.toString());
//				   
				if (content != null) {
//<<<<<<< .mine
//=======
//					   
//					//    ("结果是:" + content);
//>>>>>>> .r358
					Results results = Utils.checkResult_NNN(
							getApplicationContext(), content);
//					   
//							+ results.isRet());
					if (results != null) {
						if (results.isRet()) {
							mes.what = 5;
							// bun.putString("注册", results.getRetmsg());
							mes.setData(bun);
							handler.sendMessage(mes);
						} else {
							mes.what = 6;
							// bun.putString("注册", results.getRetmsg());
							mes.setData(bun);
							handler.sendMessage(mes);
						}
					}
				} else {
					handler.sendEmptyMessage(2);
				}
			}
		}).start();
	}

	private void Getareathread(final String df, final String panduan,
			final String type) {
		Utils.showPrgress(RegirstrationActivity.this);
		new Thread(new Runnable() {
			@Override
			public void run() {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("id", df);
				int t = Integer.parseInt(type);
				switch (t) {
				case 0:
					map.put("languageType", "cn_name");
					break;
				case 1:
					map.put("languageType", "en_name");
					break;
				case 2:
					map.put("languageType", "tw_name");
					break;
				}
				//    ("地区的upid" + map.toString());
				String content = Utils.sendRequest(map, Constants.BadiUrl
						+ "area");
				if (content != null) {
					//    ("结果是:" + content);
					Results results = Utils.checkResult_NNN(
							getApplicationContext(), content);
					if (results != null && results.getRetmsg() != null) {
						//    ("得到的结果是：" + results.getRetmsg());
						try {
							if (panduan.equals(getResources().getString(
									R.string.l_x5))) {
								areaModelssheng = JSONUtils
										.getListByJsonString(
												results.getRetmsg(),
												AreaModel.class);
								handler.sendEmptyMessage(3);
							} else if (panduan.equals(getResources().getString(
									R.string.l_x6))) {
								areaModelscity = JSONUtils.getListByJsonString(
										results.getRetmsg(), AreaModel.class);
								handler.sendEmptyMessage(4);
							}
						} catch (JSONException e) {
//							   ("解析出错");
							   
						}

					}
				} else {
					handler.sendEmptyMessage(2);
				}
			}
		}).start();
	}

	private class ZhuceInfos {
		String UserName;
		String passward;
		String mail;
		String Sex;
		String From;

		@Override
		public String toString() {
			// LogUtils.i("ZhuceInfos [UserName=" + UserName + ", passward="
			// + passward + ", mail=" + mail + ", Sex=" + Sex + ", From="
			// + From + "]");
			return "ZhuceInfos [UserName=" + UserName + ", passward="
					+ passward + ", mail=" + mail + ", Sex=" + Sex + ", From="
					+ From + "]";
		}

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v.getId() == R.id.regirstration) {

			if (panduan())// 判断
			{
				ZhuceInfos zh = new ZhuceInfos();
				zh.UserName = et_userName.getText().toString().trim();
				zh.passward = et_password.getText().toString().trim();
				zh.mail = et_mail.getText().toString().trim();
				zh.Sex = et_sex.getText().toString().trim();
				zh.From = from.getText().toString().trim();
				if (area_id != null) {
					if (sex_temp != null) {
						PutUser_Infos(zh.UserName, zh.passward, zh.mail,
								area_id, sex_temp);
					} else {
						Toast.makeText(getApplicationContext(),
								getResources().getString(R.string.l_x7), 0)
								.show();
					}
				} else {
					Toast.makeText(getApplicationContext(),
							getResources().getString(R.string.l_x8), 0).show();
				}
				// 提交
				// RegexUtils.showLoadingDialog(RegirstrationActivity.this);
			}
		}
	}

	/** 判断一些信息 这里面要加入判断是否还有相同的账号 */
	private boolean panduan() {
		boolean isSuccessful = false;
		// String userName=et_email.getText().toString();
		if (et_userName.getText().toString().trim().length() < 6
				|| et_userName.getText().toString().trim().length() > 16) {
			Toast.makeText(RegirstrationActivity.this,
					getResources().getString(R.string.l_x9), Toast.LENGTH_SHORT)
					.show();
			return false;
		} else if (!et_userName.getText().toString().trim().substring(0, 1)
				.matches("[a-zA-Z]")) {
			Toast.makeText(RegirstrationActivity.this,
					getResources().getString(R.string.l_x10),
					Toast.LENGTH_SHORT).show();
			return false;
		} else if ("".equals(et_userName.getText().toString().trim()) == true) {
			Toast.makeText(RegirstrationActivity.this,
					getResources().getString(R.string.l_xa1),
					Toast.LENGTH_SHORT).show();
			return false;
		} else if ("".equals(et_password.getText().toString().trim()) == true) {
			Toast.makeText(RegirstrationActivity.this,
					getResources().getString(R.string.l_xa2),
					Toast.LENGTH_SHORT).show();
			return false;
		} else if ((et_password.getText().toString().trim())
				.equals(et_confirm_password.getText().toString().trim()) == false) {
			Toast.makeText(RegirstrationActivity.this,
					getResources().getString(R.string.l_xa3),
					Toast.LENGTH_SHORT).show();
			return false;
		} else if ((et_password.getText().toString().trim().length() < 6 || et_password
				.getText().toString().trim().length() > 12)) {
			Toast.makeText(RegirstrationActivity.this,
					getResources().getString(R.string.l_xa4),
					Toast.LENGTH_SHORT).show();
			return false;
		} else if (RegexUtils
				.validateEmail(et_mail.getText().toString().trim()) == false) {
			Toast.makeText(RegirstrationActivity.this,
					getResources().getString(R.string.l_xa5),
					Toast.LENGTH_SHORT).show();
			return false;
		} else if ("".equals(et_sex.getText().toString().trim()) == true) {
			Toast.makeText(RegirstrationActivity.this,
					getResources().getString(R.string.l_xa6),
					Toast.LENGTH_SHORT).show();
			return false;
		} else if ("".equals(from.getText().toString().trim()) == true) {
			Toast.makeText(RegirstrationActivity.this,
					getResources().getString(R.string.l_xa7),
					Toast.LENGTH_SHORT).show();
			return false;
		}
		return true;
	}
}
